const queryString = require('querystring')
const handleBlogRouter = require('./src/router/blog.js')
const handleUserRouter = require('./src/router/user.js')
const {get,set} = require('./src/db/redis.js')
const { access } = require('./src/utils/log.js')
const SESSION_DATA ={}
//设置cookie时间
getCookieExpires=()=>{
  const d = new Date()
  d.setTime(d.getTime()+(24*60*60*1000))
  return d.toGMTString()
}
const serverHandle = (req,res)=>{
  //用于处理 post data
  const getPostData = (req)=>{
    const promise = new Promise((resolve,reject)=>{
      if (req.method !== 'POST'){
        resolve({})
        return
      }
      if (req.headers['content-type'] !== 'application/json' ){
        resolve({})
        return
      }
      let postData = ''
      req.on('data',chunk=>{
        postData += chunk.toString()
      })
      req.on('end',()=>{
        if (!postData){
          resolve({})
          return
        }
        resolve(
          JSON.parse(postData)
        )
      })
    })
    return promise
  }
  //记录access 日志
  access(`${req.method} -- ${req.url} -- ${req.headers['user-agent']}  -- ${Date.now()}`)
  //设置返回格式 JSON
  res.setHeader('content-type','application/json')
  
  //获取path
  const url = req.url
  req.path = url.split('?')[0]
  
  //解析query
  req.query = queryString.parse(url.split('?')[1])
  //解析cookie
  req.cookie = {}
  const cookie = req.headers.cookie || ''
  cookie.split(';').forEach(item=>{
    if (!item){
      return
    }
    
    let arr = item.trim().split('=')
    let key = arr[0]
    let val = arr[1]
    req.cookie[key] = val
  })
  //解析session
  let needSetCookie = false
  let userId = req.cookie.userId
  if (!userId){
    needSetCookie = true
    userId = `${Date.now()}_${Math.random()}`
    set(userId,{})
  }
  //获取session
  req.sessionId = userId
  get(userId).then(sessionData=>{
    if (sessionData === null){
      set(req.sessionId,{})
      req.session = {}
    } else {
      req.session = sessionData
    }
    return getPostData(req)
  })
  //postData 处理
  .then(postData=>{
    req.body = postData
    //处理blog路由
    const blogResult = handleBlogRouter(req,res)//返回promise
    if (blogResult){
      blogResult.then(blogData=>{
        if (needSetCookie){
          res.setHeader('Set-Cookie',`userId=${userId};path=/;httpOnly;expires=${getCookieExpires()}`)
        }
        res.end(
             JSON.stringify(blogData)
           )
      })
      return
    }
  
    //处理user路由
    const userResult = handleUserRouter(req,res)
    if (userResult){
      userResult.then(userData=>{
        if (needSetCookie){
          res.setHeader('Set-Cookie',`userId=${userId};path=/;httpOnly;expires=${getCookieExpires()}`)
        }
        res.end(
          JSON.stringify(userData)
        )
      })
      return
    }
    
    
    //未命中路由
    res.writeHead(404,{'content-type':'text/plain'})
    res.end("404 NOT Found\n")
  })
  
  
  
}
module.exports=serverHandle
